const fs = require('fs');
const { deleteFile, readFile, writeFile } = require('../action/file')
const { RESULT } = require('../config/index')

// 删除表
const deleteCollection = (tableValue, cb) => {
  deleteFile(tableValue, (err) => {
    if (err) {
      RESULT.status = 5001;
      RESULT.message = '删除失败'
    }
    cb(RESULT)
    delCollectionDetails(tableValue)
  })
}
// 删除表详情
const delCollectionDetails = (tableValue) => {
  readFile('t_object', (res) => {
    let i = res.findIndex(x => x.tableValue === tableValue)
    res.splice(i, 1)
    writeFile('t_object', res, (err) => {
      if (err) throw new Error(err)
    })
  })
}

/**
 * @descrition 删除数据到表中
 * @param {string} tableValue 
 * @param {Array} ids 
 * @param {Function} cb 
 */
const delDataToCollection = (tableValue, ids, cb) => {
  readFile(tableValue, (res) => {
    ids.forEach(id => {
      let i = res.findIndex(x => x._id === id)
      res.splice(i, 1)
    })
    writeFile(tableValue, res, (err) => {
      if (err) {
        RESULT.status = 5002
        RESULT.message = '删除失败'
      }
      cb(RESULT)
    })
  })
}

exports.deleteCollection = deleteCollection
exports.delDataToCollection = delDataToCollection